package com.tjl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tjl.model.Position;
import com.tjl.model.User;
import com.tjl.service.Impl.AdminServiceImpl;
import com.tjl.service.Impl.PositionServiceImpl;
import com.tjl.service.Impl.UserServiceImpl;
import com.tjl.util.CodeMsg;
import com.tjl.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author TJL
 * @date 2022/5/24
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private PositionServiceImpl positionService;

    @Autowired
    private JwtUtils jwtUtils;

//   @GetMapping
//   public CodeMsg getAll(){
//       return new CodeMsg(userService.list());
//   }
    @GetMapping("/list")
    public CodeMsg getAll(@RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
            int id = Integer.parseInt(claims.getId());
            QueryWrapper<Position> wrapper = new QueryWrapper<>();
            wrapper.eq("uid",id);
            List<Position> list = positionService.list(wrapper);
            if (list.size() < 1){
                throw new RuntimeException("权限不足");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }

        return new CodeMsg(userService.list());

    }

    @GetMapping("/{id}")
    public CodeMsg getOne(@PathVariable Integer id){
        return new CodeMsg(userService.getById(id));
    }

    @GetMapping()
    public CodeMsg getUserinfo(@RequestHeader String token){

        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }

        return new CodeMsg(userService.getById(claims.getId()));
    }

    @PostMapping
    public CodeMsg addUser(@RequestBody User user){
        boolean isOk = false;
        try{
            isOk =  userService.save(user);
        }catch (Exception e){
            return  new CodeMsg(false,"账号重复");
        }
        return  new CodeMsg(isOk);
    }

    @PutMapping
    public CodeMsg putUser(@RequestBody User user,@RequestHeader String token){

        Claims claims;
        try {
             claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }

        user.setId(Integer.parseInt(claims.getId()));
        System.out.println("xxxxxxxxxxxx"+user);
       return new CodeMsg(userService.updateById(user));
    }
}
